package com.feeyo.groundservice.wifi.util

import android.util.Log
import com.blankj.utilcode.util.NetworkUtils
import com.feeyo.android.base.BaseApplication
import com.feeyo.android.util.FyLog
import java.net.InetAddress

/**
 *作者：QLH on 2020-11-30
 *描述：初始化灯箱
 */
internal object InitLightBoxIP {

    /**
     * 初始化灯箱IP，获取到后保存到本地，监听状态：data class LightBoxIPEvent(val has:Boolean)
     * **/
    @JvmStatic
    fun initLightBoxIp() {
        LightBoxIPEvent(false).post()
        LightBoxCache.saveLightBoxIP("")
        FyLog.e("LightBox", "准备获取灯箱IP")
        if (!APUtil.isWifiApOpen(BaseApplication.getContext())) {
            toast("请开启热点，再打开App")
            return
        }
        if (NetworkUtils.isConnected() && (NetworkUtils.is4G() || NetworkUtils.is5G())) {
            val localIp = APUtil.getWifiApIpAddress()
            val apIp = localIp?.substringBeforeLast(".")
            Log.e("平板IP段", localIp?:"无主机ip")

            for (i in 2..255) {
                val ip = "$apIp.$i"
                if (localIp != ip) {//排除本机ip地址
                    Thread {
                        try {
                            val success = getClientIP(ip)
                            if (success) {//通过ping获取灯箱IP
                                val url = "http://${ip}:8080"
                                Log.e("灯箱服务器IP:", url)
                                LightBoxCache.saveLightBoxIP(url)
                                LightBoxIPEvent(true).post()
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }.start()
                }
            }
        } else {
            toast("请开启4G网络")
        }
    }

    private fun getClientIP(targetIp: String): Boolean {
        //循环ping测试
        val timeOut = 3000
        return InetAddress.getByName(targetIp).isReachable(timeOut)
    }
}